<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="证件号码" prop="cardId">
            <el-input v-model="queryParams.cardId" placeholder="请输入证件号码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contact">
            <el-input v-model="queryParams.contact" placeholder="请输入联系电话" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="岗位" prop="post">
            <el-input v-model="queryParams.post" placeholder="请输入岗位" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="健康证编号" prop="hcNumber">
            <el-input v-model="queryParams.hcNumber" placeholder="请输入健康证编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="健康证有效期" prop="hcValidity">
            <el-input v-model="queryParams.hcValidity" placeholder="请输入健康证有效期" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="培训证等级" prop="tcLevel">
            <el-input v-model="queryParams.tcLevel" placeholder="请输入培训证等级" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="培训证有效期" prop="tcValidity">
            <el-input v-model="queryParams.tcValidity" placeholder="请输入培训证有效期" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['canteen:employee:add']">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['canteen:employee:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['canteen:employee:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['canteen:employee:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="employeeList"
        @selection-change="handleSelectionChange"
        @header-click="handleCellMouseEnter"
        v-bind:border="showborder"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="sex" v-if="columns[0].visible">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>

        <el-table-column label="证件号码" align="center" prop="cardId" v-if="columns[1].visible" />
        <el-table-column label="岗位" align="center" prop="post" v-if="columns[2].visible" />
        <el-table-column label="健康证照片" align="center" prop="hc" width="100" v-if="columns[3].visible">
          <template #default="scope">
            <image-preview :src="scope.row.ossUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="健康证编号" align="center" prop="hcNumber" v-if="columns[4].visible" />
        <el-table-column label="健康证有效期" align="center" prop="hcValidity" v-if="columns[5].visible" />
        <el-table-column label="培训证等级" align="center" prop="tcLevel" v-if="columns[6].visible" />
        <el-table-column label="培训证有效期" align="center" prop="tcValidity" v-if="columns[7].visible" />
        <el-table-column label="校区" align="center" prop="schoolCampusName" v-if="columns[19].visible" />
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[17].visible" />
        <el-table-column label="联系电话" align="center" prop="contact" v-if="columns[18].visible" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['canteen:employee:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['canteen:employee:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改从业人员管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="employeeFormRef" :model="form" :rules="rules" :label-width="formLabelWidth">
        <campus @schoolCampus="handleSchoolCampus" :selectValue="form.schoolCampusId"></campus>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="证件号码" prop="cardId">
              <el-input v-model="form.cardId" placeholder="请输入证件号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位" prop="post">
              <el-input v-model="form.post" placeholder="请输入岗位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="健康证照片" prop="hc">
              <image-upload v-model="form.hc" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="健康证编号" prop="hcNumber">
              <el-input v-model="form.hcNumber" placeholder="请输入健康证编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="健康证有效期" prop="hcValidity">
              <el-input v-model="form.hcValidity" placeholder="请输入健康证有效期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="培训证等级" prop="tcLevel">
              <el-input v-model="form.tcLevel" placeholder="请输入培训证等级" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="培训证有效期" prop="tcValidity">
              <el-input v-model="form.tcValidity" placeholder="请输入培训证有效期" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Employee" lang="ts">
import {
    listEmployee,
    getEmployee,
    delEmployee,
    addEmployee,
    updateEmployee
} from '@/api/canteen/employee';
import {
        EmployeeVO,
        EmployeeQuery,
        EmployeeForm
} from '@/api/canteen/employee/types';

import {listByIds} from '@/api/system/oss';
import campus from '@/components/campus/index.vue';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no, sys_user_sex, nation } = toRefs<any>(proxy?.useDict('sys_yes_no', 'sys_user_sex', 'nation'));
const employeeList = ref<EmployeeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const names = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const formLabelWidth = '120px';
const showborder = ref(false)

const queryFormRef = ref<ElFormInstance>();
const employeeFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData: EmployeeForm = {
                    employeeId: undefined,
                    name: undefined,
                    sex: undefined,
                    cardId: undefined,
                    post: undefined,
                    hc: undefined,
                    hcNumber: undefined,
                    hcValidity: undefined,
                    tcLevel: undefined,
                    tcValidity: undefined,
                    schoolCampusId: undefined,
                    remark: undefined,
                    contact: undefined,
}
const data = reactive<PageData<EmployeeForm, EmployeeQuery>>({
    form: {...initFormData},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
                        name: undefined,
                        sex: undefined,
                        cardId: undefined,
                        post: undefined,
                        hc: undefined,
                        hcNumber: undefined,
                        hcValidity: undefined,
                        tcLevel: undefined,
                        tcValidity: undefined,
                        schoolCampusId: undefined,
                        contact: undefined,
        params: {
        }
    },
    rules: {

                        name: [
                        {
                            required: true, message: "姓名不能为空", trigger: "blur" }
                    ],
                        sex: [
                        {
                            required: true, message: "性别不能为空", trigger: "change" }
                    ],
                        cardId: [
                        {
                            required: true, message: "证件号码不能为空", trigger: "blur" }
                    ],
                        post: [
                        {
                            required: true, message: "岗位不能为空", trigger: "blur" }
                    ],
                        hc: [
                        {
                            required: true, message: "健康证照片不能为空", trigger: "blur" }
                    ],
                        hcNumber: [
                        {
                            required: true, message: "健康证编号不能为空", trigger: "blur" }
                    ],
                        hcValidity: [
                        {
                            required: true, message: "健康证有效期不能为空", trigger: "blur" }
                    ],
                        tcLevel: [
                        {
                            required: true, message: "培训证等级不能为空", trigger: "blur" }
                    ],
                        tcValidity: [
                        {
                            required: true, message: "培训证有效期不能为空", trigger: "blur" }
                    ],
                        schoolCampusId: [
                        {
                            required: true, message: "请选择所属校区", trigger: "blur" }
                    ],
                        remark: [
                        {
                            required: true, message: "备注不能为空", trigger: "blur" }
                    ],
                    contact: [
                        {
                            required: true, message: "联系电话不能为空", trigger: "blur" }
                    ]

    }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询从业人员管理列表 */
const getList = async () => {
    loading.value = true;
    const res = await listEmployee(queryParams.value);
        employeeList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}

/** 查詢從業人員管理列表 (修改後的版本) */
// const getList = async () => {
//     loading.value = true;
//     // 步驟 1: 先獲取包含 oss_id 的原始員工列表
//     const res = await listEmployee(queryParams.value);
//     if (!res.rows || res.rows.length === 0) {
//         employeeList.value = [];
//         total.value = 0;
//         loading.value = false;
//         return;
//     }

//     // 步驟 2: 從列表中提取出所有不為空的 hc (也就是 oss_id)
//     const ossIds = res.rows.map(row => row.hc).filter(id => id);

//     // 步驟 3: 如果有 oss_id，就去批次查詢對應的 URL
//     if (ossIds.length > 0) {
//         // 請注意：這裡假設 listByIds 接收的是用逗號分隔的字串
//         // 如果它接收的是陣列，請改成 listByIds(ossIds)
//         const ossRes = await listByIds(ossIds.join(','));

//         if (ossRes.code === 200 && ossRes.data) {
//             // 步驟 4: 建立一個從 oss_id 到 url 的映射表，方便快速查找
//             const urlMap = new Map(ossRes.data.map(item => [item.ossId, item.url]));

//             // 步驟 5: 遍歷原始員工列表，將 hc 的值從 oss_id 替換為真實的 URL
//             res.rows.forEach(row => {
//                 if (row.hc && urlMap.has(row.hc)) {
//                     row.hc = urlMap.get(row.hc) as string; // 替換為 URL
//                 }
//             });
//         }
//     }

//     // 步驟 6: 將處理好的列表賦值給 employeeList
//     employeeList.value = res.rows;
//     total.value = res.total;
//     loading.value = false;
// }


/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
        employeeFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: EmployeeVO[]) => {
    ids.value = selection.map(item => item.employeeId);
    names.value = selection.map(item => item.name);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加从业人员管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: EmployeeVO) => {
    reset();
    const _employeeId = row?.employeeId || ids.value[0]
    const res = await getEmployee(_employeeId);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改从业人员管理";
}


/** 提交按钮 */
const submitForm = () => {
        employeeFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.employeeId) {
                await updateEmployee(form.value).finally(() =>  buttonLoading.value = false);
            } else {
                await addEmployee(form.value).finally(() =>  buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("修改成功");
            dialog.visible = false;
            await getList();
        }
    });
}

/** 删除按钮操作 */
const handleDelete = async (row?: EmployeeVO) => {
    const _employeeIds = row?.employeeId || ids.value;
    const _subjectNames=row?.name || names.value;
    await proxy?.$modal.confirm('是否确认删除从业人员"' + _subjectNames + '"的数据项？').finally(() => loading.value = false);
    await delEmployee(_employeeIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
    proxy?.download('canteen/employee/export', {
        ...queryParams.value
    }, `employee_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
    getList();
});


/** 列信息 */
const columns = ref([
            {key: 0, label: `性别`, visible: true},
            {key: 1, label: `证件号码`, visible: true},
            {key: 2, label: `岗位`, visible: true},
            {key: 3, label: `健康证照片`, visible: true},
            {key: 4, label: `健康证编号`, visible: true},
            {key: 5, label: `健康证有效期`, visible: true},
            {key: 6, label: `培训证等级`, visible: true},
            {key: 7, label: `培训证有效期`, visible: true},
            {key: 8, label: `租户id`, visible: true},
            {key: 9, label: `校区id`, visible: true},
            {key: 10, label: `创建部门`, visible: true},
            {key: 11, label: `创建人`, visible: true},
            {key: 12, label: `创建时间`, visible: true},
            {key: 13, label: `修改人`, visible: true},
            {key: 14, label: `修改时间`, visible: true},
            {key: 15, label: `删除标志`, visible: true},
            {key: 16, label: `版本`, visible: true},
            {key: 17, label: `备注`, visible: true},
            {key: 18, label: `联系电话`, visible: true},
            {key: 19, label: `校区`, visible: true},
]);


function handleCellMouseEnter() {
    showborder.value = !showborder.value;
}



/**
 * 从 campus组件中获取校区
 * @param {*} value
 */
function handleSchoolCampus(value: number | undefined) {

     data.form.schoolCampusId = value;

}
</script>
